//
//  KAOldMobileVerVC.swift
//  kano
//
//  Created by Frank on 2024/10/31.
//

import Foundation
import UIKit
import RxCocoa
import RxSwift
import JXSegmentedView

class KAOldMobileVerVC: KABaseVC {
    var codeToken: String = ""
    var verifyToken: String = ""
    var buttonHandle: ((Int, String) -> ())?
    
    private let disposeBag = DisposeBag()

    lazy var var_cornerView: UIView = {
        let var_cornerView = UIView()
        var_cornerView.backgroundColor = UIColor.white
        var_cornerView.layer.cornerRadius = kscale(30)
        var_cornerView.layer.masksToBounds = true
        var_cornerView.frame = CGRectMake(kscale(20), kscale(20), var_screenWidth-kscale(40), kscale(330))
        return var_cornerView
    }()
    
    lazy var var_titleLabel: UILabel = {
        let var_titleLabel = UILabel()
        var_titleLabel.x = kscale(20)
        var_titleLabel.y = kscale(32)
        var_titleLabel.width = var_cornerView.width-kscale(40)
        var_titleLabel.height = kscale(66)
        var_titleLabel.textAlignment = .left
        var_titleLabel.font = UIFont.systemFont(ofSize: kscale(24), weight: .regular)
        var_titleLabel.textColor = .black
        var_titleLabel.text = "Please enter the correct image verification code"
//        var_titleLabel.sizeToFit()
        var_titleLabel.numberOfLines = 2
        return var_titleLabel
    }()
    
    lazy var var_mobileLabel: UILabel = {
        let var_mobileLabel = UILabel()
        var_mobileLabel.frame = CGRectMake(kscale(20), var_titleLabel.bottom+kscale(12), var_cornerView.width-kscale(40), kscale(32))
        var_mobileLabel.font = UIFont.systemFont(ofSize: kscale(16), weight: .regular)
        var_mobileLabel.textColor = .black
        var_mobileLabel.text = "+234 " + KAUserManager.shared.user.mobile
        return var_mobileLabel
    }()
    
    lazy var var_pwdView: KAVerCodeView = {
        var_pwdView = KAVerCodeView(placeHolder: "Please enter the captcha", limit: 4, rightBtnHide: true)
        var_pwdView.x = kscale(20)
        var_pwdView.y = var_mobileLabel.bottom + kscale(20)
        var_pwdView.size = CGSizeMake(var_cornerView.width-kscale(40)-kscale(120), kscale(48))
        //var_pwdView.rightBtn.isHidden = true
        var_pwdView.contentTF.keyboardType = .default
        return var_pwdView
    }()
    
    private var captcheId: String = ""
    private lazy var verifyImageV: UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage(named: "home_numCollect")
        imageView.isUserInteractionEnabled = true
        imageView.size = CGSizeMake(kscale(114), kscale(48))
        imageView.x = var_pwdView.right + kscale(6)
        imageView.y = var_pwdView.top
        let tap = UITapGestureRecognizer(target: self, action: #selector(generatePic))
        imageView.addGestureRecognizer(tap)
        return imageView
    }()
    
    lazy var var_signBtn: UIButton = {
        let var_signBtn = UIButton(frame: CGRectMake(kscale(48), var_pwdView.bottom+kscale(32), var_cornerView.width-kscale(96), kscale(50.0)))
        var_signBtn.setTitle("Next Step", for: .normal)
        var_signBtn.setTitleColor(.white, for: .normal)
        var_signBtn.titleLabel?.font = UIFont.systemFont(ofSize: kscale(17), weight: .bold)
        var_signBtn.backgroundColor = .colorBDBDF5
        var_signBtn.layer.cornerRadius = kscale(25)
        var_signBtn.layer.masksToBounds = true
        var_signBtn.addTarget(self, action: #selector(ka_signButtonClick), for: .touchUpInside)
        return var_signBtn
    }()
}

extension KAOldMobileVerVC {
    override func viewDidLoad() {
        super.viewDidLoad()
        ka_setUI()
        ka_bindUI()
        generatePic()
    }
    
    func ka_setUI() {
        view.backgroundColor = .colorf2f2f5
        
        view.addSubview(var_cornerView)
        var_cornerView.addSubview(var_titleLabel)
        var_cornerView.addSubview(var_mobileLabel)
        var_cornerView.addSubview(var_pwdView)
        var_cornerView.addSubview(verifyImageV)
        var_cornerView.addSubview(var_signBtn)
    }
    
    func ka_bindUI() {
        var_pwdView.contentTF.rx.text
            .orEmpty
            .map { text in
                return (text.count == 4) ? .themeColor : .colorBDBDF5
            }
            .bind(to: var_signBtn.rx.backgroundColor)
            .disposed(by: disposeBag)
    }
    
    @objc func ka_signButtonClick() {
        guard var_pwdView.contentTF.text!.count == 4 else {
            view.makeToast("Please enter 4 digits or letters"); return
        }
        ka_verifyPicCode()
    }
    
    @objc private func generatePic() {
        view.showLoading()
        loginProvider.request(.picVerify()) { result in
            self.view.hideLoading()
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KAContent>.handleResponseData(response.data) { isSuccess, message, response in
                        if isSuccess {
                            guard let content = response?.content else { return }
                            self.captcheId = content.captcheId
                            self.verifyImageV.kf.setImage(with: URL(string: NetConfig.fullImgUrl(path: self.captcheId)))
                        } else {
                            self.view.makeToast(message)
                        }
                    }
                }else {
                    self.view.makeToast(badNetWorking)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
    
    @objc func ka_verifyPicCode() {
        let paramDic: [String: Any] = [
            "userGid": KAUserManager.shared.user.userGid,
            "loginMobile": KAUserManager.shared.user.mobile,
            "mobile": KAUserManager.shared.user.mobile,
            "captchaId": captcheId,
            "captchaCode": var_pwdView.contentTF.text!
        ]
        loginProvider.request(.validateMobile(paramDic)) { [self] result in
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KAContent>.handleResponseData(response.data) { isSuccess, message, response in
                        if isSuccess {
                            guard let content = response?.content else {
                                view.makeToast("Verification failure"); return
                            }
                            //0,弹框提示
                            if content.status == 0 {
                                let subStr = "You have not verified your identity. You cannot change your phone number. It is recommended to use a new phone number for re-registration."
                                let alert = KAAlertView.alert(withTitle: "Prompt", subtitle: subStr) { clickedTitle in
                                }
                                alert.addAction(KAAlertAction(title: "Go to Register", titleColor: .blue, backgroundColor: .clear) { action in
                                    //切到输入手机号页面
                                    KADBDBManager.ka_removeCurrentUser()
                                    KAUserManager.shared.userLogout()
                                })
                                alert.show()
                            } else if buttonHandle != nil {
                                self.buttonHandle!(content.status, content.name)
                            }
                        } else {
                            self.view.makeToast(message)
                        }
                    }
                }else {
                    self.view.makeToast(badNetWorking)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
}

extension KAOldMobileVerVC: JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        view.backgroundColor = .colorf2f2f5
        return view
    }
}
